﻿var express = require('express');
var router = new express.Router();
var reportCtller = require('../../Controllers/reportCtller');
var dbQryCtl = require('../../Controllers/dbQueryCtller');
//var nodeExcel = require('excel-export');
var fs = require("fs");
//var xlsx = require('node-xlsx').default;

/**
 * 对所有/admin/下的url进行登入拦截，没有权限的全部转到/user/下，未登入的转到/login
 * <必需放在需拦截的请求前>
 */
router.all('*', function (req, res, next) {
    if (req.session.user) {
        if (req.session.user.role >= 9) { next(); }
        else { res.redirect("/user/"); }
    } else {        
        console.log("[" + req.method + "]ori_url:" + req.originalUrl + "|url:" + req.url);
        res.redirect("/login");
    }
});

router.get('/report', function (req, res) {
    res.render('admExportReport', { title: '统计报表' });
}).post('/report', function (req, res) {
    var dtF = req.body.dtF,
        dtT = req.body.dtT;
    reportCtller.exportExcel(dtF, dtT, function (err, data) {
        if (err) { res.end(JSON.stringify({ data: err, code: 901 })); }
        else {
            //var wbData = nodeExcel.execute(data);
            //res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            //res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
            //res.end(wbData, 'binary');

            //var row = data.cols.reduce(function (prev, next) {
            //    if (!(prev instanceof Array)) { prev = [prev.caption] }
            //    prev.push(next.caption);
            //    return prev;
            //});
            //var rows = [row];
            //res.end(JSON.stringify(rows.concat(data.rows)));

            res.end(JSON.stringify(data));
        }
    });
});

router.get('/setting', function (req, res) {
    res.render('SysInfoSetting', { title: '系统设置' });
});

router.post('/sys-set-upd', function (req, res) {
    var dt = JSON.parse(req.body.dataTable),
        tabID = req.body.tabID,
        rows = JSON.parse(req.body.dataTable),
        delRows = JSON.parse(req.body.toDel);
    dbQryCtl.dbBaseInfoUpd(tabID, rows, delRows, function (err, data) {
        if (err) { res.end(JSON.stringify({ data: err, code: 901 })); }
        else {
            dbQryCtl.dbQuery(tabID, function (err, data) {
                if (err) { res.end(JSON.stringify({ data: err, code: 902 })); }
                else { res.end(JSON.stringify({ data: data, code: 200 })); }
            });
            //res.end(JSON.stringify({ data: data, code: 200 }));
        }
    });
});

module.exports = router;